package com.lcy.web.resource;

import com.lcy.web.utils.CommonUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by loucunyin on 12/19/16.
 * 用于解析 xml 资源文件
 */
public abstract class XmlResource {
    private ConcurrentHashMap<String, String> mResMap;
    private String mName;

    public XmlResource() {
        initMap();
    }

    /**
     * 从 string.properties 读取内容到 hash map
     */
    private  void initMap() {
        // 获取根节点
        Document document = getDocument();
        Element node = document.getRootElement();
        if(node == null){
            return;
        }

        // 初始化 map
        mResMap = new ConcurrentHashMap<>();

        // 读取数据存入 map
        for (Iterator<?> iterator = node.elementIterator(); iterator.hasNext(); ) {
            Element element = (Element) iterator.next();
            if(element.getName().equals(mName)) {
                Attribute name = element.attribute("id");
                String key = name.getValue();
                String value = element.getText();
                if (CommonUtils.checkString(key) && CommonUtils.checkString(value)) {
                    mResMap.put(key, value);
                }
            }
        }
    }

    /**
     * @return string.properties 的 document 对象
     */
    private  Document getDocument() {
        SAXReader reader = new SAXReader();
        try {
            return reader.read(getResourceStream());
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    private InputStream getResourceStream(){
        return this.getClass().getClassLoader().getResourceAsStream(getXmlPath());
    }

    /**
     * @return string.properties 的路径
     */
    protected abstract String getXmlPath();


    /**
     * @param id id
     * @return string
     */
     protected String getResById(String id) {
        return getResById(id,null);
    }

    protected String getResById(String id, String defaultValue) {
        if (mResMap != null) {
            return mResMap.get(id);
        }
        return defaultValue;
    }
}
